package com.zlm.controller;


import com.google.code.kaptcha.Producer;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 验证码请求controller(前后不分离因此不需要返回数据)
 */

@Controller
public class VerifyCodeController {

    @Resource
    private Producer producer;

    @GetMapping("/vc.jpg")
    public void verifyCode(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException {

        // 生成验证码
        String verifyCode = producer.createText();

        // 验证码保存在session里面(当然后面肯定是保存在redis里面的)
        session.setAttribute("verifyCode", verifyCode);

        // 设置图片类型
        response.setContentType("image/png");
        // 生成图片
        BufferedImage bi = producer.createImage(verifyCode);

        // 响应图片
        ServletOutputStream os = response.getOutputStream();
        ImageIO.write(bi, "jpg", os);
    }
}
